var fs = require("fs")
var os = require("os");
const process = require('process');
// process.exit(1);
const csvParser = require('csv-parser');
const sourceFile = './csv/filter.csv';
const tagetFile = './csv/calc.csv';
const keys = [
  'time', 'fv01', 'fv02', 'fv03',
  'fv04', 'fv05', 'fv06', 'fv07',
  'fv08', 'fv09', 'fv10', 'fv11',
  'fv12', 'fv13', 'fv14', 'fv15',
  'fv16', 'fv17', 'fv18', 'fv19',
  'fv20', 'fv21', 'fv22', 'fv23',
  'fv24', 'fv25', 'fv26', 'fv27',
  'fv28', 'fv29', 'fv30', 'fv31',
  'fv32', 'fv33', 'fv34', 'fv35',
  'fv36', 'val1', 'val2', 't'
];

console.log('----- calc start -----');
fs.appendFileSync(tagetFile, keys.join(',') + os.EOL);
let ele = {};
fs.createReadStream(sourceFile)
  .pipe(csvParser())
  .on('data', (data) => {
    if (!ele.time) {
        data.val1 = 0;
        data.val2 = 0;
        data.t = 0;
    } else {
      data.val1 = data.fv35 - ele.fv35;
      data.val2 = data.fv36 - ele.fv36;
      data.t = subTime(data.time, ele.time);
    }
    writeFile(tagetFile, data);
    ele = Object.assign({}, data);
  })
  .on('end', () => {
    console.log('----- calc end -----');
  });


function writeFile(filePath, data){
    let arr = [];
    keys.forEach(val=>{
      arr.push(data[val]);
    })
    const text = arr.join(',')
	  fs.appendFileSync(filePath, text + os.EOL);
}

function subTime(time1, time2) {
  return ((new Date(time1) - new Date(time2)) / 1000).toFixed(0);
}
